#include "button_bsp.h"

#define BUTTON_PRESS_COUNT 20
#define BUTTON_LONGPRESS_COUNT 200
#define BUTTON_LONGLONGPRESS_COUNT 2000
#define BUTTON_SOLONGPRESS_COUNT 10000

static uint8_t button_status = BUTTON_NOPRESS;
static uint8_t button_press = BUTTON_NOPRESS;

void buttonInit(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    gpio_mode_set(BUTTON_PORT, GPIO_MODE_INPUT, GPIO_PUPD_PULLDOWN, BUTTON_PIN);
}

void buttonDeinit(void)
{
    rcu_periph_clock_disable(RCU_GPIOA);
    pmu_wakeup_pin_enable(PMU_WAKEUP_PIN0);
}

static uint8_t buttonRead(void)
{
    return SET == gpio_input_bit_get(BUTTON_PORT, BUTTON_PIN) ? 1 : 0;
}

void buttonProcess(void)
{
    static uint8_t press = 0;
    static uint16_t filter_count = 0;
    uint8_t status = buttonRead();

    if (status == 0 && press == 0)
        press = 1;
    else if (status == 1 && press == 1)
        filter_count++;

    if (status == 1 && filter_count >= BUTTON_PRESS_COUNT && filter_count < BUTTON_LONGPRESS_COUNT)
        button_status = BUTTON_PRESS;
    else if (status == 1 && filter_count >= BUTTON_LONGPRESS_COUNT && filter_count < BUTTON_LONGLONGPRESS_COUNT)
    {
        button_status = BUTTON_LONGPRESS;
    }
    else if (status == 1 && filter_count >= BUTTON_LONGLONGPRESS_COUNT && filter_count < BUTTON_SOLONGPRESS_COUNT)
    {
        button_status = BUTTON_LONGLONGPRESS;
    }
    else if (status == 1 && filter_count >= BUTTON_SOLONGPRESS_COUNT)
    {
        button_status = BUTTON_SOLONGPRESS;
        filter_count = BUTTON_SOLONGPRESS_COUNT;
    }
    else if (status == 0 && press == 1 && filter_count >= BUTTON_PRESS_COUNT)
    {
        button_status = BUTTON_CLICK;
        filter_count = 0;
        press = 0;
    }
}

uint8_t buttonGetPress(void)
{
    return buttonRead();
}

uint8_t buttonGetStatus(void)
{
    uint8_t ret = button_status;
    button_status = BUTTON_NOPRESS;
    return ret;
}